<?php
namespace app\manage\controller;
use fast\Tree;
use think\Log;

class AuthGroup extends Base
{
    public function index()
    {
        $count = model('AuthGroup')->countNum('',false);
        $authGroup = model('AuthGroup')->getInfosByMap('', '', false);
        return $this->fetch('',[
            'authGroup' => $authGroup,
            'count' => $count
        ]);
    }

    public function edit()
    {
        $id = input('id');
        $group = model('AuthGroup')->getArrayByMap(['id'=>$id], '', false);
        return self::showJsonReturnCodeData('1001',$group,'');

    }

    /**
     * 读取角色权限树
     *
     * @internal
     */
    public function roletree()
    {
        $model = model('AuthGroup');
        $id = $this->request->param("id");
        $currentGroupModel = NULL;
        $id && $currentGroupModel = $model->get($id);
        if (!$id || $currentGroupModel)
        {
            $id = $id ? $id : NULL;
            $ruleList = collection(model('AuthRule')->order('listorder', 'desc')->select())->toArray();

            Tree::instance()->init($ruleList);

            //是否是超级管理员
            $superadmin = model('AuthGroup')->isSuperAdmin($id);

            //当前拥有的规则ID集合
            $currentRuleIds = model('AuthGroup')->getRuleIds($id);

            $parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');


            $hasChildrens = [];
            foreach ($parentRuleList as $k => $v)
            {
                if ($v['haschild'])
                    $hasChildrens[] = $v['id'];
            }
            $parentRuleIds = array_map(function($item) {
                return $item['id'];
            }, $parentRuleList);
            $nodeList = [];

            foreach ($parentRuleList as $k => $v)
            {
                $state = array('selected' => in_array($v['id'], $currentRuleIds) && !in_array($v['id'], $hasChildrens));
                $nodeList[] = array('id' => $v['id'], 'parent' => $v['parent_id'] ? $v['parent_id'] : '#', 'text' => $v['title'], 'type' => 'menu', 'state' => $state);
            }

            return self::showJsonReturnCodeData('1001',$nodeList,'');
        }
        else
        {
            return self::showReturnCode(1002,'分组错误');
        }
    }


    /*
     * 授权
     * */
    public function authorize()
    {
        $id = input('id');
        // 获取无限极分类权限
        $authRule = model('AuthRule')->getInfosByMap('', '', false,'listorder desc,id desc');
        $authRuleRes = model('AuthRule')->sort($authRule);
//        dump($authRuleRes);die;

        $group = model('AuthGroup')->get($id);

        $ruleArr = explode(',', $group->rules);

        return $this->fetch('', [
            'authRuleRes'=>$authRuleRes,
            'group'=>$group,
            'ruleArr'=>$ruleArr
        ]);
    }

    public function delete()
    {
        if($this->request->isAjax()){
            $id = input('post.id');

            $infoTemp = model('AuthGroupAccess')->getArrayByMap(['group_id'=>$id],'','',false);
            if($infoTemp){
                return $this->showReturnCode(1009,'该角色组下有管理员,无法删除');
            }
            $res = model('AuthGroup')->destroy($id);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除角色组成功,操作ID: '.$id);
                return $this->showReturnCode(1001,'删除角色组成功');
            }else{
                return $this->showReturnCode(1009,'删除角色组失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function save()
    {
        if(request()->isAjax()){
            try{
                $data = input('post.');


                $id = input('id');
                $save_data['title'] = $data['title'];
                $save_data['rules'] = $data['rules'];
                if(isset($id) && $id){
                    $save_data['id'] = $id;
                }

                $result = $this->editData(false,'AuthGroup','AuthGroup',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){
                        $msg = '编辑';
                    }else{
                        $msg = '添加';
                    }
                    $result['msg'] = $msg.'角色组成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,$msg.'角色组【'.$save_data['title'].'】成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }
}